﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.UI.WebControls;
using DotNetNuke.Entities.Modules.Communications;

using CharityGamesOnline.Modules.Game;
using CharityGamesOnline.Modules.Common;

namespace CharityGamesOnline.Modules.Event
{
    public partial class EventList : CGOBase
    {
        private int charityID = 0;

        public int CharityID
        {
            get
            {
                if (charityID == 0)
                {
                    if ((Request.QueryString["CharityID"] != null))
                    {
                        charityID = Int32.Parse(Request.QueryString["CharityID"]);
                    }                    
                }

                return charityID;
            }
        }
        
        public int EventDetailTabID
        {
            get 
            {
                if (!Null.IsNull(Settings["EventDetailTabID"]))
                {
                    return Int32.Parse(Settings["EventDetailTabID"].ToString());
                }
                else
                    return TabId;                
            } 
        }

        public int GameDetailTabID
        {
            get
            {
                if (!Null.IsNull(Settings["GameDetailTabID"]))
                {
                    return Int32.Parse(Settings["GameDetailTabID"].ToString());
                }
                else
                    return 0;
            }
        }
        
        public bool boolViewArchive
        {
            get
            {
                if (!Null.IsNull(Settings["ShowArchive"]))
                {
                    return Boolean.Parse(Settings["ShowArchive"].ToString());
                }
                else
                    return false;
            }
 
        }

        #region Event Handler

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    BindData();                    
                }
            }

            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }        

        protected void dlEvent_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            HyperLink lnkEventDetail = e.Item.FindControl("lnkEventDetail") as HyperLink;
            Label lbDonationMoney = e.Item.FindControl("lbDonationMoney") as Label;
            Label lbGameRemainCount = e.Item.FindControl("lbGameRemainCount") as Label;
            ImageButton btnPlay = e.Item.FindControl("btnPlay") as ImageButton;
            
            int eventID = Int32.Parse(DataBinder.Eval(e.Item.DataItem, "EventID").ToString());            
            int maxEnrollCount = Int32.Parse(DataBinder.Eval(e.Item.DataItem, "MaxEnrollment").ToString());
            bool allowEnroll = Boolean.Parse(DataBinder.Eval(e.Item.DataItem, "Signups").ToString());
            DateTime dateEnd = Convert.ToDateTime(DataBinder.Eval(e.Item.DataItem, "DateEnd"));
            DateTime dateBegin = Convert.ToDateTime(DataBinder.Eval(e.Item.DataItem, "DateBegin"));
            int intGameTotal = ctrlEnroll.GetPlayedCount(PortalId, eventID, 0, 0, 0);
            int intGameEnroll = ctrlEnroll.GetPlayedCount(PortalId, eventID, 0, 0, (int)GameEnrollmentInfo.STATUS.ENROLLED);
            int playedCount = intGameTotal - intGameEnroll;

            if (maxEnrollCount == 0)
            {
                lbGameRemainCount.Text = Localization.GetString("unlimitedGameRemain",LocalResourceFile);
            }
            else
            {
                lbGameRemainCount.Text = (maxEnrollCount - playedCount).ToString();                
            }
            decimal totalAmount = ctrlEnroll.GetMoneyCount(PortalId, eventID);
            decimal unpaidAmount = ctrlEnroll.GetMoneyCount(PortalId, eventID, 0, 0, (int)GameEnrollmentInfo.STATUS.ENROLLED);
            decimal donateAmount = totalAmount - unpaidAmount;

            lbDonationMoney.Text = string.Format(Localization.GetString("doationFormat", LocalResourceFile), donateAmount); 
            

            if (EventDetailTabID == TabId || EventDetailTabID<0)
            {
                lnkEventDetail.NavigateUrl = Globals.NavigateURL(EventDetailTabID, string.Empty, "mid=" + ModuleId.ToString(), "mctl=EventDetail", "EventID=" + eventID.ToString());
            }
            else
            {
                lnkEventDetail.NavigateUrl = Globals.NavigateURL(EventDetailTabID, string.Empty, "EventID=" + eventID.ToString());
            }

            btnPlay.Enabled = true;
            btnPlay.ImageUrl = "images/playnow.png";

            if (DateTime.Now > dateEnd)
            {
                btnPlay.Enabled = false;
                btnPlay.ImageUrl = "images/expired.png";
            }
            else if (DateTime.Now < dateBegin)
            {
                btnPlay.Enabled = false;
                btnPlay.ImageUrl = "images/startsoon.png";
            }
            else if (!IsEnrolled(eventID))
            {
                if (!allowEnroll)
                {
                    btnPlay.Enabled = false;
                    btnPlay.ImageUrl = "images/locked.png";
                }                
                else if (maxEnrollCount != 0 && playedCount >= maxEnrollCount)
                {
                    btnPlay.Enabled = false;
                    btnPlay.ImageUrl = "images/outnumbered.png";
                }                
            }
        }

        protected void dlEvent_ItemCreated(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {
            ImageButton btnPlay = e.Item.FindControl("btnPlay") as ImageButton;
            if (btnPlay != null)
            {                
                btnPlay.Click += new ImageClickEventHandler(btnPlay_Click);
            }            
        }        

        protected void btnPlay_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btnPlay = sender as ImageButton;
            if (btnPlay!=null && GameDetailTabID != 0)
            {
                Response.Redirect(Globals.NavigateURL(GameDetailTabID, string.Empty, "EventID=" + btnPlay.CommandArgument));
            }
        }

        #endregion

        #region Private Function

        private void BindData()
        {
            EventController ctrlEvent = new EventController();
            List<EventInfo> lstEvent;

            if (boolViewArchive)
            {
                DateTime beginDate = DateTime.Now.Date.AddYears(-1);
                lstEvent = ctrlEvent.GetEvents(PortalId, CharityID, Null.NullDate, DateTime.Now.Date);
            }
            else
            {
                lstEvent = ctrlEvent.GetEvents(PortalId, CharityID, DateTime.Now.Date, Null.NullDate);
            }

            dlEvent.DataSource = lstEvent;
            dlEvent.DataBind();
        }

        private bool IsEnrolled(int eventID)
        {
            bool enrolled = false;
            GameController ctrlGame = new GameController();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            List<GameInfo> lstGame = ctrlGame.GetGames(PortalId, eventID);
            if (lstGame.Count > 0)
            {
                int gameID = lstGame[0].GameID;
                int enrollID = ctrlEnroll.GetUncompletedEnrollID(PortalId, eventID, gameID, UserId);
                if (enrollID != 0)
                {
                    enrolled = true;
                }
            }
            return enrolled;
        }

        #endregion

        #region Public Function
        
        public void BindData(int intCharity)
        {
            charityID = intCharity;
            BindData();
        }
        
        #endregion
    }
}